//
//  AuctionOrderListVC.swift
//  LeGou
//
//  Created by lxm on 2022/10/17.
//

import UIKit

class AuctionOrderListVC: ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct, PayCheckerDelegate {
    //MARK: --------------------属性--------------------
    var listData = [Order]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    var type : AuctionOrderState = .all
    
    var paychecker : PayChecker<String> = PayChecker()
    // 0 微信 1 支付宝
    var payType = 0
    
    var onRefresh : (()->())?
    //MARK: --------------------UI控件--------------------
    let tableView = UITableView().then { t in
        t.separatorStyle = .none
        t.tableFooterView = UIView()
    }
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        tableView.mj_header?.beginRefreshing()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        title = ""
        setUpTableView()
        view.backgroundColor = "#F5F5F5".zm.hex()
        paychecker.delegate = self
        tableView.estimatedRowHeight = 100
    }
    
    func setUpTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = "#F5F5F5".zm.hex()
        tableView.zm.register(nibName: "AuctionOrderCell", reuserId: "AuctionOrderCell")
        tableView.showsVerticalScrollIndicator = false
        view.addSubview(tableView)
        addRefresh(scrollView: tableView) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.loadList()
            if let onRefresh = self.onRefresh {
                onRefresh()
            }
        }
        addNodataScrollView(scrollView: tableView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
    }
    
    func addConstraints() {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        ZMPayManager.shard.payCallBack.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .success:
                self.tableView.mj_header?.beginRefreshing()
            default:
                ZMToast.showToast(title: resp.rawValue)
            }
        }).disposed(by: disposeBag)
        
        
        
        ZMNotification.shard.subject.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .refreshOrderList, .auctionRefersh:
                self.tableView.mj_header?.beginRefreshing()
            default:break
            }
        }).disposed(by: disposeBag)
        
        
    }
    
    func loadList() {
        var pa = ["limit" : pageSize, "page" : page, "state" : type.rawValue]
        
        ZMUtil.listRequest(type: Order.self, api: AuctionAPI.myAuction(pa)) { resp in
            self.listRequest(resp)
        }
    }
    
    func cancelOrder(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否要取消当前订单", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.cancelOrder(["id" : id]).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    //  确认收货
    func ensureReceive(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否确认收货", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.suerReceive(id).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    
    func showPay(_ orderNo : String, money : String) {
        let v = ZMUtil.loadNibViewFullScreen(nibName: OrderChoosePayView.self)
        v.price.text = money
        v.payMoney = Double(money) ?? 0
        v.onPayCallback = { [weak self] type in
            guard let self = self else {return}
            var payType = ""
            switch type {
                case .alipay:
                    payType = "alipay"
                    break;
                case .wechat:
                    payType = "weixin"
                    break;
                case .balancePay:
                    payType = "yue"
                case .ckPay:
                    payType = "mallYue"
                case .integral:
                    payType = "integral"
            }
            var pa = ["orderNo" : orderNo, "payType" : payType] as [String : Any]
            if type == .balancePay || type == .ckPay {
                CommonService.shared.showPsdInput(title : "请输入交易密码", money: money, left : "", right : "") { psd, close in
                    pa["tradePwd"] = psd
                    self.sendPay(pa: pa, orderNo: orderNo, payType: payType) { ok in
                        close(ok)
                        v.removeFromSuperview()
                    }
                }
            } else {
                self.sendPay(pa: pa, orderNo: orderNo, payType: payType) { ok in
                    v.removeFromSuperview()
                }
            }
        }
        APPWindow?.addSubview(v)
    }
    
    func sendPay(pa : [String : Any], orderNo : String, payType : String, complete:@escaping (_ ok : Bool)->()) {
        VIPMallAPI.payInfo(pa).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            if payType == "yue" || payType == "mallYue" {
                self.tableView.mj_header?.beginRefreshing()
            } else {
                let payStr = JSON(resp)["alipayRequest"].stringValue
                if payType == "weixin" {
                    ZMPayManager.shard.wechatPay(resp, orderNum: orderNo)
                } else {
                    ZMPayManager.shard.aliPayWithInfo(payStr, orderNum: orderNo)
                }
                self.payType = payType == "weixin" ? 0 : 1
                self.paychecker.checkData.accept(orderNo)
                self.paychecker.startCheck()
            }
            complete(true)
        }, onError: { _ in
            complete(false)
        }).disposed(by: self.disposeBag)
    }
    
    // 跳转查看物流
    func goExpress(_ orderNo : String) {
        let vc = ZMLogisticsVC()
        vc.orderNo = orderNo
        navigationController?.pushViewController(vc, animated: true)
    }
    
    //  删除订单
    func ensureDelete(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否要删除当前订单", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.deleteOrder(id).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    // 显示课程详情
    func showTheLesson(downloadLink : String, password : String) {
        let v = ZMUtil.loadNibViewFullScreen(nibName: LessonDetailView.self)
        v.downloadLink = downloadLink
        v.password = password
        v.resetUI()
        APPWindow?.addSubview(v)
    }
    
    //MARK: --------------------delegate--------------------
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = listData[indexPath.row]
        let vc = AuctionDetailVC()
        vc.id = data.ahGoodsRecordId
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AuctionOrderCell") as! AuctionOrderCell
        let data = listData[indexPath.row]
        cell.compoundStatus.isHidden = true
        cell.time.text = data.createTime
        cell.img.zm.setImage(urlStr: data.image)
        cell.name.text = data.storeName
        cell.orderNum.text = "竞购编号：" + data.bidNo
        cell.info.text = "围观\(data.currentViewer)次 已出价\(data.bidPeopleNum)人"
        cell.join.setTitle("参与 \(data.frequency) 次", for: .normal)
        
        cell.eismateStack.isHidden = false
        cell.estH.constant = 22
        cell.moneyBtn.setTitle("¥\(data.joinShare.zm.xmToString(keep: 2))", for: .normal)
//        cell.currentMoney.text = data.nowAmount.zm.toString(keep: 2)
        cell.cj.isHidden = true
        cell.givePrice.isHidden = true
        cell.addvance.isHidden = true
        cell.rightBtn.isHidden = true
        cell.dateNum.text = "第\(data.ahCount)期"
        cell.endDate = nil
        cell.rightBtn.backgroundColor = "#DE3F26".zm.hex()
        if data.state == .process {
            cell.eismate.setTitle("预估", for: .normal)
            cell.cj.isHidden = false
            cell.givePrice.isHidden = false
            cell.givePrice.text = data.nowAmount.zm.toString(keep: 2)
            cell.addvance.isHidden = false
            cell.addvance.setTitle(data.bidState == 0 ? "出局" : "领先", for: .normal)
            cell.addvance.backgroundColor = data.bidState == 0 ? "#CCCCCC".zm.hex() : Style.mainColor
            cell.stateLabel.text = "竞购中"
            cell.stateLabel.textColor = UIColor.zm.color333333()
            cell.dqj.text = "当前价¥"
            cell.currentMoney.text = data.currentPrice.zm.toString(keep: 2)
        } else if data.state == .success  || data.state == .waitPay {
            cell.eismate.setTitle("赚", for: .normal)
            cell.stateLabel.text = "竞购成功"
            cell.stateLabel.textColor = UIColor.zm.color333333()
            cell.rightBtn.isHidden = false
            cell.dqj.text = "竞购价¥"
            cell.currentMoney.text = data.currentPrice.zm.toString(keep: 2)
            if data.finalPaid == 1 {
                // 已经付了尾款
                if data.giveType == 2 {
                    cell.compoundStatus.text = data.conflateRefundStatusStr
                    cell.compoundStatus.isHidden = false
                    cell.rightBtn.isHidden = true
                } else {
                    cell.rightBtn.isHidden = false
                    cell.rightBtn.setTitle("商品订单", for: .normal)
                    cell.rightBtn.setTitleColor(UIColor.zm.color333333(), for: .normal)
                    cell.rightBtn.backgroundColor = .white
                    cell.rightBtn.layer.borderWidth = 0.5
                    cell.rightBtn.layer.borderColor = Style.lineColor.cgColor
                    cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                        let vc = VIPOrderDetail()
                        vc.orderNo = data.orderId
                        self.navigationController?.pushViewController(vc, animated: true)
                    }).disposed(by: cell.disposeBag)
                }
            } else {
                // 未支付
                cell.endDate = data.expTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss")
                cell.rightBtn.setTitle("去付尾款 ￥\(data.payPrice.zm.toString(keep: 2))", for: .normal)
                cell.rightBtn.backgroundColor = "#DE3F26".zm.hex()
                cell.rightBtn.layer.borderWidth = 0
                cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                    // 去付尾款
                    let vc = AuctionCreateOrderVC()
                    vc.recordId = data.ahGoodsRecordId
                    self.navigationController?.pushViewController(vc, animated: true)
                }).disposed(by: cell.disposeBag)
                    cell.timer.subscribe(onNext:{ [weak cell] resp in
                        guard let cell = cell else {return}
                        cell.updateDate()
                    }).disposed(by: cell.disposeBag)
            }
        } else if data.state == .over {
            cell.eismate.setTitle("赚", for: .normal)
            cell.stateLabel.text = "竞购结束"
            cell.stateLabel.textColor = UIColor.zm.color999999()
            cell.currentMoney.text = data.currentPrice.zm.toString(keep: 2)
            cell.dqj.text = "竞购价¥"
            if data.finalPaid == 0, data.deductionBail == 1 {
                cell.endTime.text = "超时未支付"
            } else {
                cell.endTime.isHidden = true
            }
        } else if data.state == .toNext {
            cell.dqj.text = "流拍价¥"
            cell.eismateStack.isHidden = true
            cell.estH.constant = 0
            cell.stateLabel.text = "已流拍"
            cell.stateLabel.textColor = UIColor.zm.color999999()
            cell.currentMoney.text = data.currentPrice.zm.toString(keep: 2)
        }
        cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            let vc = MyBids()
            vc.ahGoodsRecordId = data.ahGoodsRecordId
            self.navigationController?.pushViewController(vc, animated: true)
        }).disposed(by: cell.disposeBag)
        
        cell.updateDate()
        return cell
    }
    
    func check(_ keepOn: @escaping (() -> ())) {
        XMLogger.tracking("开始检测支付")
        guard let currentPayInfo = paychecker.checkData.value else {return}
        let api = payType == 0 ? VIPMallAPI.wxCheck(currentPayInfo) : VIPMallAPI.alipayCheck(currentPayInfo)
        api.rxRequest(type: Bool.self).subscribe(onNext:{ [unowned self] resp in
            if resp {
                // 支付成功
                self.tableView.mj_header?.beginRefreshing()
                self.paychecker.checkData.accept(nil)
                XMLogger.tracking("检测成功")
            } else {
                XMLogger.tracking("检测失败---调用keepOn")
                keepOn()
            }
        }, onError: { _ in
//            ZMAppShareData.share.requestVIPInfo()
        }).disposed(by: disposeBag)
    }
    
}

extension AuctionOrderListVC {
    struct Order : HandyJSON {
        var ahCount: Int = 0
        var ahGoodsRecordId: Int = 0
        var bidNo = ""
        var bidPeopleNum: Int = 0
        var bidState: Int = 0
        var createTime = ""
        var currentPrice = 0.0
        var currentViewer: Int = 0
        var finalPaid: Int = 0
        var frequency: Int = 0
        var image = ""
        var joinShare = 0.0
        var nowAmount = 0.0
        var payPrice = 0.0
        var state : AuctionOrderState = .success
        var storeName = ""
        var expTime = ""
        var deductionBail = 0
        // 合成退款：0否 1已奖励 2已返还
        var conflateRefundStatusStr = ""
        // 获得方式：0实物 1积分 2加入合成库(合成中)
        var giveType = 0
        var orderId = ""
    }
}
